package edu.uw.cs.cse461.sp12.SNet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;

import edu.uw.cs.cse461.sp12.OS.OS;
import edu.uw.cs.cse461.sp12.OS.RPCService;
import edu.uw.cs.cse461.sp12.OS.SNetController;
import edu.uw.cs.cse461.sp12.androidSNet.R;
import edu.uw.cs.cse461.sp12.util.DB461.DB461Exception;
import edu.uw.cs.cse461.sp12.util.SNetDB461.PhotoRecord;
import edu.uw.cs.cse461.sp12.utilIP.MyContext;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.MediaStore;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SNetActivity extends Activity {
	
	private TextView ipField;
	public static String ipAddress;
	private String storage;
	private ImageView myImage;
	private ImageView chosenImage;
	private Button takePicButton;
	private Button choosePicButton;
	private Button updateDataButton;
	
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 461;
	private static final int CHOOSE_PICTURE_ACTIVITY_REQUEST_CODE = 462;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MyContext.context = this;
        setContentView(R.layout.main);
        ipField = ((TextView)findViewById(R.id.ip));
        ipField.setText("");
        
        //get all screen items we may need, ie buttons, imageviews etc
        myImage = ((ImageView)findViewById(R.id.myImage));
        chosenImage = ((ImageView)findViewById(R.id.chosenImage));
        takePicButton = ((Button)findViewById(R.id.takePic));
        choosePicButton = ((Button)findViewById(R.id.choosePic));
        updateDataButton = ((Button)findViewById(R.id.updateData));
        
        
        
        
        WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int wifiIPInt = wifiInfo.getIpAddress();
        String wifiIP = Formatter.formatIpAddress(wifiIPInt);
        ipAddress = wifiIP;
        
        ipField.setText(ipAddress);
        
        choosePicButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              chooseGallery2();
            }
          });
        
        takePicButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              takePic();
            }
          });
        
        updateDataButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	Intent i = new Intent(MyContext.context, UpdateData.class);
            	// Set the request code to any code you like, you can identify the
            	// callback via this code
            	startActivity(i);
            }
          });
        
        new Thread(){
            public void run() {
              // worker thread starts running asynchronously here
            	String configFilename = "foo.bar.config.ini.png";
            
                Properties config = new Properties();
                
                try {
                	config.load(getAssets().open(configFilename));
                	storage = config.getProperty("snet.gallery");
        			OS.boot(getAssets().open(configFilename));
        			OS.startRPCServices(OS.rpcServiceClasses);
        			//set photos if they exist
        	        File myPhoto;
        	        File chosenPhoto;
        			try {
        				System.out.println("getting my photo");
        				myPhoto = ((SNetController)OS.getRPCService("snet")).getMyPhoto();
        				System.out.println(myPhoto.getPath());
        				chosenPhoto = ((SNetController)OS.getRPCService("snet")).getChosenPhoto();
        				if(myPhoto.exists()){
        				    Bitmap myBitmap = BitmapFactory.decodeFile(myPhoto.getAbsolutePath());
        				    myImage.setImageBitmap(myBitmap);
        				}
        				if(chosenPhoto.exists()){
        				    Bitmap myBitmap = BitmapFactory.decodeFile(chosenPhoto.getAbsolutePath());
        				    //chosenImage.setImageBitmap(myBitmap);
        				}
        			} catch (DB461Exception e1) {
        				// TODO Auto-generated catch block
        				e1.printStackTrace();
        			}
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		} catch (Exception e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
              runOnUiThread(new Runnable() {
                public void run() {
                  
                }
              });
            }
          }.start();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	File myPhoto;
        File chosenPhoto;
		try {
			System.out.println("getting my photo");
			SNetController c = (SNetController)OS.getRPCService("snet");
			if (c != null) {
				myPhoto = c.getMyPhoto();
				chosenPhoto = c.getChosenPhoto();
				if(myPhoto != null && myPhoto.exists()){
					System.out.println(myPhoto.getPath());
				    Bitmap myBitmap = BitmapFactory.decodeFile(myPhoto.getAbsolutePath());
				    myImage.setImageBitmap(myBitmap);
				}
				if(chosenPhoto != null && chosenPhoto.exists()){
				    Bitmap myBitmap = BitmapFactory.decodeFile(chosenPhoto.getAbsolutePath());
				    chosenImage.setImageBitmap(myBitmap);
				}
			}
		} catch (DB461Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
        //localPort.setText(msg);
		
        
    }
    
    
    
    private void takePic() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		 startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
	}
    
    private void chooseGallery2() {
    	Intent intent = new Intent(Intent.ACTION_PICK,
    	          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    	intent.setType("image/*");
    	startActivityForResult(intent, CHOOSE_PICTURE_ACTIVITY_REQUEST_CODE);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (resultCode != RESULT_CANCELED) {
	    	if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
	    		Bitmap photoBmp = (Bitmap)data.getExtras().get("data");
	        	myImage.setImageBitmap(photoBmp);
	        	try {
	        		String filename = storage + System.currentTimeMillis() + ".bmp";
	        	       FileOutputStream out = new FileOutputStream(filename);
	        	       photoBmp.compress(Bitmap.CompressFormat.PNG, 90, out);
	        	       out.close();
	        	       System.out.println("File written " + filename);
	        	       File file = new File(filename);
	        	       updateGallery();
	        	       ((SNetController)OS.getRPCService("snet")).setMyPhoto(file);
	        	} catch (Exception e) {
	        	       e.printStackTrace();
	        	}
	    	} else if (requestCode == CHOOSE_PICTURE_ACTIVITY_REQUEST_CODE) {
	    		Uri selectedImage = data.getData();
	    		String[] filePathColumn = {MediaStore.Images.Media.DATA};
	
	    		Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	    		cursor.moveToFirst();
	
	    		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	    		String filePath = cursor.getString(columnIndex);
	    		cursor.close();
	    		File imgFile = new  File(filePath);
	    		if(imgFile.exists()){
	
	    		    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
	
	    		    
	    		    chosenImage.setImageBitmap(myBitmap);
	    		    try {
						((SNetController)OS.getRPCService("snet")).setChosenPhoto(imgFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (DB461Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	
	    		}
	    		
	    	}
    	}
    	
    }
    
    public void updateGallery(){
    	// Try to update gallery viewer
        sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }
}
